﻿using Fishing.Abstractions;
using Fishing.Common;
using Fishing.Model;
using System;
using System.IO;
using System.Text.Json;

namespace Fishing.Core
{
    public class SettingsService : ISettingsService
    {
        private readonly string _settingsPath = Constants.SettingsPath;
        private readonly JsonSerializerOptions _serializerOptions = new() { WriteIndented = true };

        public ISettings Settings { get; private set; }

        public SettingsService()
        {
            Load();
        }

        public void Load()
        {
            try
            {
                using var fileStream = File.Open(_settingsPath, FileMode.Open);

                Settings = JsonSerializer.Deserialize<Settings>(fileStream) ?? throw new ArgumentNullException("json null/corrupt");
            }
            catch
            {
                Settings = new Settings();
                Save();
            }
        }

        public void Save()
        {
            var json = JsonSerializer.Serialize(Settings as Settings, _serializerOptions);
            using var writer = new StreamWriter(_settingsPath);

            try
            {
                writer.Write(json);
            }
            finally
            {
                writer.Flush();
                writer.Close();
            }
        }
    }
}
